package org.rayworks.downloadutils;

import org.rayworks.downloadutils.DownloadReceiver.DownloadCompleteListener;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends Activity implements DownloadCompleteListener {

	private DownloadReceiver mReceiver;
	private ImageView mImage;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		mImage = (ImageView) findViewById(R.id.image_remote);
		Button mBtn = (Button) findViewById(R.id.button_loader);
		mBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent i = new Intent();
				i.putExtra("url", remoteUrl);
				i.setClass(MainActivity.this, DownloadService.class);
				startService(i);
			}
		});
		
		mReceiver = new DownloadReceiver();
		mReceiver.setListener(this);
		registerReceiver(mReceiver, new IntentFilter(DownloadReceiver.ACTION_TYPE));
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	@Override
	protected void onPause() {
		unregisterReceiver(mReceiver);
		super.onPause();
	}

	@Override
	public void onLoadedComplete(byte[] data) {
		if(data != null){
			Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
			if(bmp != null){
				mImage.setImageBitmap(bmp);
			}
		}
	}

	private String remoteUrl = "http://lh6.googleusercontent.com/-4CN4X4t0M1k/URqufPozWzI/AAAAAAAAAbs/8wK41lg1KPs/s160-c/Caterpillar.jpg";

}
